<template>
  <div class="workflow-run-page">
    <div class="run-left">
      <div class="workflow-selector">
        <h3>选择工作流</h3>
        <el-select v-model="selectedWorkflow" placeholder="请选择工作流" @change="onWorkflowChange">
          <el-option
            v-for="workflow in workflows"
            :key="workflow.id"
            :label="workflow.name"
            :value="workflow.id"
          />
        </el-select>
      </div>
      
      <div v-if="selectedWorkflow" class="input-params">
        <h3>输入参数</h3>
        <el-form :model="inputParams" label-width="100px">
          <el-form-item label="测试参数">
            <el-input v-model="inputParams.testParam" placeholder="请输入测试参数" />
          </el-form-item>
          <el-form-item label="用户输入">
            <el-input
              v-model="inputParams.userInput"
              type="textarea"
              :rows="4"
              placeholder="请输入用户输入内容"
            />
          </el-form-item>
        </el-form>
      </div>
      
      <el-button 
        type="primary" 
        class="run-btn" 
        @click="handleRun"
        :loading="isRunning"
        :disabled="!selectedWorkflow"
      >
        {{ isRunning ? '执行中...' : '开始运行' }}
      </el-button>
      <el-button
        type="success"
        class="export-btn"
        style="margin-top: 12px; width: 120px; align-self: center;"
        @click="handleExport"
        :disabled="!selectedWorkflow"
      >
        导出工作流
      </el-button>
    </div>
    
    <div class="run-right">
      <div class="output-label">执行结果</div>
      <div v-if="isRunning" class="running-status">
        <el-progress :percentage="executionProgress" :show-text="false" />
        <p>正在执行工作流...</p>
      </div>
      <div v-else-if="executionResult" class="result-content">
        <div class="result-header">
          <span class="result-status" :class="executionResult.success ? 'success' : 'error'">
            {{ executionResult.success ? '执行成功' : '执行失败' }}
          </span>
          <span class="result-time">{{ executionTime }}</span>
        </div>
        <pre class="run-output">{{ outputJson }}</pre>
      </div>
      <div v-else class="no-result">
        <p>暂无执行结果</p>
      </div>
    </div>
  </div>
</template>

<script>
import { listWorkflow, executeWorkflow, exportWorkflow } from '@/api/system/workflow'

export default {
  name: 'WorkflowRun',
  data() {
    return {
      workflows: [],
      selectedWorkflow: null,
      inputParams: {
        testParam: '测试参数',
        userInput: '这是一个测试输入'
      },
      isRunning: false,
      executionResult: null,
      executionTime: '',
      executionProgress: 0
    }
  },
  computed: {
    outputJson() {
      return this.executionResult ? JSON.stringify(this.executionResult, null, 2) : ''
    }
  },
  mounted() {
    this.loadWorkflows()
  },
  methods: {
    async loadWorkflows() {
      try {
        const response = await listWorkflow({})
        if (response.code === 200) {
          this.workflows = response.rows || response.data || []
        }
      } catch (error) {
        this.$message.error('加载工作流列表失败: ' + error.message)
      }
    },
    
    onWorkflowChange(workflowId) {
      this.executionResult = null
      this.executionTime = ''
    },
    
    async handleRun() {
      if (!this.selectedWorkflow) {
        this.$message.warning('请先选择工作流')
        return
      }
      
      this.isRunning = true
      this.executionProgress = 0
      this.executionResult = null
      
      // 模拟执行进度
      const progressTimer = setInterval(() => {
        if (this.executionProgress < 90) {
          this.executionProgress += Math.random() * 20
        }
      }, 200)
      
      try {
        const startTime = new Date()
        const response = await executeWorkflow(this.selectedWorkflow, this.inputParams)
        
        clearInterval(progressTimer)
        this.executionProgress = 100
        
        if (response.code === 200) {
          this.executionResult = response.data
          this.executionTime = new Date().toLocaleString()
          this.$message.success('工作流执行成功')
        } else {
          this.executionResult = {
            success: false,
            error: response.msg || '执行失败'
          }
          this.$message.error('执行失败: ' + response.msg)
        }
      } catch (error) {
        clearInterval(progressTimer)
        this.executionResult = {
          success: false,
          error: error.message
        }
        this.$message.error('执行失败: ' + error.message)
      } finally {
        this.isRunning = false
      }
    },

    async handleExport() {
      if (!this.selectedWorkflow) {
        this.$message.warning('请先选择工作流');
        return;
      }
      try {
        const res = await exportWorkflow(this.selectedWorkflow);
        if (res && res.code === 200 && res.data) {
          const blob = new Blob([JSON.stringify(res.data, null, 2)], { type: 'application/json' });
          const url = URL.createObjectURL(blob);
          const a = document.createElement('a');
          a.href = url;
          a.download = `${res.data.name || 'workflow'}.json`;
          document.body.appendChild(a);
          a.click();
          document.body.removeChild(a);
          URL.revokeObjectURL(url);
          this.$message.success('导出成功');
        } else {
          this.$message.error('导出失败: ' + (res.msg || '未知错误'));
        }
      } catch (error) {
        this.$message.error('导出失败: ' + error.message);
      }
    }
  }
}
</script>

<style scoped>
.workflow-run-page {
  display: flex;
  background: #fafafa;
  min-height: 100vh;
  padding: 40px 0 0 0;
}

.run-left {
  flex: 1;
  max-width: 40%;
  min-width: 320px;
  padding: 40px 32px 0 60px;
  display: flex;
  flex-direction: column;
  gap: 24px;
}

.workflow-selector h3,
.input-params h3 {
  margin: 0 0 12px 0;
  font-size: 16px;
  font-weight: 600;
  color: #333;
}

.workflow-selector .el-select {
  width: 100%;
}

.input-params {
  background: #fff;
  padding: 20px;
  border-radius: 8px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

.run-btn {
  width: 120px;
  font-size: 16px;
  margin-top: 8px;
  align-self: center;
}

.run-right {
  flex: 1;
  background: #fcfcfc;
  min-width: 320px;
  padding: 40px 60px 0 32px;
  border-left: 1px solid #f0f0f0;
}

.output-label {
  font-size: 16px;
  font-weight: 600;
  margin-bottom: 16px;
  color: #222;
}

.running-status {
  text-align: center;
  padding: 40px 20px;
}

.running-status p {
  margin-top: 16px;
  color: #666;
}

.result-content {
  background: #fff;
  border-radius: 8px;
  padding: 20px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

.result-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 16px;
  padding-bottom: 12px;
  border-bottom: 1px solid #eee;
}

.result-status {
  font-weight: 600;
  padding: 4px 12px;
  border-radius: 4px;
  font-size: 14px;
}

.result-status.success {
  background: #f0f9ff;
  color: #0ea5e9;
}

.result-status.error {
  background: #fef2f2;
  color: #ef4444;
}

.result-time {
  font-size: 12px;
  color: #666;
}

.run-output {
  background: #f8f8f8;
  border-radius: 8px;
  padding: 18px 20px;
  font-size: 14px;
  color: #3a3a3a;
  min-height: 200px;
  margin: 0;
  white-space: pre-wrap;
  font-family: 'Monaco', 'Menlo', 'Ubuntu Mono', monospace;
  overflow-x: auto;
}

.no-result {
  text-align: center;
  padding: 60px 20px;
  color: #999;
}
</style> 